#include "mainwindow.h"
#include <QFileDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setGeometry(0, 0, 800, 480);
    textEdit = new QTextEdit();
    vBoxLayout = new QVBoxLayout();
    hBoxLayout = new QHBoxLayout();
    vWidget = new QWidget();
    hWidget = new QWidget();
    openPushButton = new QPushButton();
    closePushButton = new QPushButton();

    openPushButton->setMinimumHeight(50);
    openPushButton->setMaximumWidth(120);
    closePushButton->setMinimumHeight(50);
    closePushButton->setMaximumWidth(120);

    openPushButton->setText("打开");
    closePushButton->setText("关闭");

    /* 设置关闭按钮为不可用属性，需要打开文件才设置为可用属性 */
    closePushButton->setEnabled(false);

    hBoxLayout->addWidget(openPushButton);
    hBoxLayout->addWidget(closePushButton);
    hWidget->setLayout(hBoxLayout);

    vBoxLayout->addWidget(textEdit);
    vBoxLayout->addWidget(hWidget);
    vWidget->setLayout(vBoxLayout);

    setCentralWidget(vWidget);

    connect(openPushButton, SIGNAL(clicked()),
            this, SLOT(openFile()));
    connect(closePushButton, SIGNAL(clicked()),
            this, SLOT(closeFile()));
}

MainWindow::~MainWindow()
{
}

bool MainWindow::openFile()
{

    QString fileName = QFileDialog::getOpenFileName(this);

    file.setFileName(fileName);

    if(!file.exists()) {
        return false;
    }


    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }
    /* 使用文本流读取文件 */
    QTextStream stream(&file);
    /* 读取文本到textEdit */
    textEdit->setPlainText(stream.readAll());

    openPushButton->setEnabled(false);
    closePushButton->setEnabled(true);

    file.close();
    return true;
}

void MainWindow::closeFile()
{
    if(!openPushButton->isEnabled()) {



        if(!file.open(QIODevice:: WriteOnly | QIODevice::Text)) {
            return;
        }
        /* 用文本流读取文件 */
        QTextStream stream(&file);

        QString str = textEdit->toPlainText();
        /* 使用流提取运算符，写入文本流 */
        stream << str;

        textEdit->clear();
        file.close();


        openPushButton->setEnabled(true);
        closePushButton->setEnabled(false);

    }

}
